package com.yingyi.org.controller;

import com.yingyi.basic.annotation.PreAuthorize;
import com.yingyi.basic.exception.BusinessException;
import com.yingyi.basic.util.ExcelUtils;
import com.yingyi.basic.util.JsonResult;
import com.yingyi.basic.util.PageList;
import com.yingyi.org.domain.Shop;
import com.yingyi.org.domain.ShopAuditLog;
import com.yingyi.org.dto.ShopDto;
import com.yingyi.org.query.ShopQuery;
import com.yingyi.org.service.IShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Api(value = "店铺的API",tags="店铺相关的CRUD功能")
@RestController
@RequestMapping("/shop")
public class ShopController {

    @Autowired
    private IShopService shopService;
    /**
     * restful风格的请求
     * 使用动作+url来确定请求
     * url：定位资源
     * 动作：具体要做什么
     */


    /**
     *  url: http://localhost:8080/Shop
     * 查询所有
     * @RequestMapping(value = "", method = RequestMethed.Get)
     */
    @PreAuthorize(name = "查询所有店铺数据", sn = "shop:queryAll")
    @ApiOperation(value = "查询所有店铺数据" )
    @GetMapping
    public List<Shop> queryAll(){
        try {
            return shopService.queryAll();
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<Shop>();
        }
    }

    /**
     * 根据id查询
     * url: http://localhost:8080/Shop
     * method: Get
      */
    @PreAuthorize(name = "通过ID查询店铺数据", sn = "shop:queryById")
    @ApiOperation(value = "通过ID查询")
    @ApiImplicitParams({
            //@ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
            //@ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
            @ApiImplicitParam(name="id", value="编号", required = true, paramType = "path", dataType = "Long")
    })
    @GetMapping("/{id}")
    public Shop queryById(@PathVariable Long id){
        try {
            return shopService.queryById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 增加或修改
     * url: http://localhost:8080/Shop
     * @RequestBody 从请求体中获取数据
     */
    //@ApiParam(name="待操作的Shop对象，id为null表示添加，id非null表示修改",required = true)
    @PreAuthorize(name = "增加或修改店铺信息", sn = "shop:save")
    @ApiOperation(value = "增加或修改店铺信息" )
    @ApiImplicitParams({
            //@ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
            //@ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
            @ApiImplicitParam(name="Shop",  value="待操作的Shop对象，id为null表示添加，id非null表示修改",required = true,
                    paramType = "query", dataType = "com.yingyi.org.domain.Shop"
            )
    })
    @PostMapping
    public JsonResult save(@RequestBody Shop Shop){
        try {
            if(Shop.getId()==null){
                //添加操作
                shopService.insert(Shop);
            }else{
                //修改操作
                shopService.update(Shop);
            }
            System.out.println("in save >>>>>>>>");
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMessage("操作失败");
        }
    }

    /**
     * 删除操作
     * url: http://localhost:8080/Shop/1
     * 操作 Delete
     * @ApiParam(name="ID属性",required = true)
     */
    @PreAuthorize(name = "通过ID删除店铺数据", sn = "shop:deleteById")
    @ApiOperation(value = "通过ID删除店铺数据" )
    @ApiImplicitParams({
            //@ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
            //@ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
            @ApiImplicitParam(name="id", value="ID属性",required = true, paramType = "path",
            dataType = "Long")
    })
    @DeleteMapping("/{id}")
    public JsonResult deleteById(@PathVariable Long id){
        try {
            shopService.delete(id);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMessage("删除失败");
        }
    }

    /**
     * 批量删除
     */
    @PreAuthorize(name = "批量删除店铺数据", sn = "shop:patchDelete")
    @ApiOperation(value = "批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name="ids", value="待删除的ID集合",required = true, paramType = "query",
                    dataType = "java.util.ArrayList")
    })
    @PatchMapping
    public JsonResult patchDelete(@RequestBody List<Long> ids){
        try {
            shopService.patchDelete(ids);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMessage("删除失败，请稍后重试！");
        }
    }




    /**
     * 分页
     * url http://localhost:8080/Shop/
     * 方式 Post
     * @ApiParam(name="查询的参数",required = true)
     */
    @PreAuthorize(name = "分页查询和条件查询店铺数据", sn = "shop:pageQuery")
    @ApiOperation(value = "分页查询和条件查询" )
    @ApiImplicitParams({
            //@ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
            //@ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
            @ApiImplicitParam(name="query", value="查询的参数",required = true,
                    paramType = "query", dataType = "com.yingyi.org.query.ShopQuery"
            )
    })
    @PutMapping
    public PageList<Shop> pageQuery(@RequestBody ShopQuery query){
        try {
            return shopService.queryData(query);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageList<Shop>();
        }
    }


    /**
     * 店铺入驻
     * @return
     */
    @PostMapping("/settlement")
    public JsonResult settlement(@RequestBody Shop shop){
        try {
            shopService.settlement(shop);
            return JsonResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return JsonResult.me().setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMessage("系统繁忙，请稍后重试");
        }

    }

    /**
     * 店铺审核 通过
     * @return
     */
    @PostMapping("/audit/pass")
    public JsonResult shopAuditPass(@RequestBody ShopAuditLog log){
        try {
            shopService.shopAuditPass(log);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMessage("系统繁忙，请稍后重试");
        }

    }


    /**
     * 店铺审核 驳回
     * @return
     */
    @PostMapping("/audit/reject")
    public JsonResult shopAuditReject(@RequestBody ShopAuditLog log){
        try {
            shopService.shopAuditReject(log);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMessage("系统繁忙，请稍后重试");
        }

    }

    /**
     * 店铺激活
     *  用户通过点击邮件中的激活链接发送请求携带了一个shop_id参数
     *  请求路径： http://localhost:8080/shop/active/id
     * @param id
     * @return
     */
    @GetMapping("/active/{id}")
    public String shopActive(@PathVariable Long id){
        try {
            shopService.active(id);


             return "激活成功!!! 登录地址 http://localhost:8081/login";
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "激活失败，稍后重试";

    }


    /**
     * 导出excel文件
     */
    @PreAuthorize(name = "导出店铺数据", sn = "shop:exportExcel")
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse resp){
        try {
            //查询出所有的数据，保存到集合中
            List<Shop> list = shopService.queryAll();
            ExcelUtils.exportExcel(list, "入驻店铺明细信息", "入驻店铺", Shop.class, "shop.xlsx", resp);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    /**
     * excel文件的上传
     * @param file
     */
    @PreAuthorize(name = "导入店铺数据", sn = "shop:importExcel")
    @PostMapping("/importExcel")
    public void importExcel(@RequestPart(value = "file", required = true) MultipartFile file){
        try {
            //前端上传文件，后台通过file接收再由excel工具类解析，结果放到集合中，再存入数据库中（批量存入）
            List<Shop> shops = ExcelUtils.importExcel(file, 1, 1, Shop.class);

            shops.forEach(System.out::println);
            shopService.patchInsert(shops);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @GetMapping("/getEcharts")
    public List<ShopDto> getEcharts(){
        try {
            List<ShopDto> list =  shopService.getEcharts();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<ShopDto>();
        }
    }


}
